// lib/services/umeng_analytics.dart
import 'package:flutter/foundation.dart';
import 'package:umeng_common_sdk/umeng_common_sdk.dart';

// 友盟埋点的封装
class UmengAnalytics {
  static bool _isInitialized = false;

  static Future<void> init() async {
    if (_isInitialized) return;

    try {
      // 初始化友盟SDK
      UmengCommonSdk.initCommon(
        '64c8c3d6a1a164591b5f0768', // androidAppKey
        '64d49ae8838db11fc2cac619', // iosAppKey
        'APP', // channel
      );

      UmengCommonSdk.setPageCollectionModeAuto();

      _isInitialized = true;
      debugPrint('友盟统计初始化完成');
    } catch (e) {
      debugPrint('友盟统计初始化失败: $e');
    }
  }

  static void onPageStart(String pageName) {
    if (!_isInitialized) return;
    UmengCommonSdk.onPageStart(pageName);
    debugPrint('页面开始: $pageName');
  }

  static void onPageEnd(String pageName) {
    if (!_isInitialized) return;
    UmengCommonSdk.onPageEnd(pageName);
    debugPrint('页面结束: $pageName');
  }

  static Future<bool> onEvent(
    String eventId, {
    Map<String, dynamic>? properties,
  }) async {
    if (!_isInitialized) return false;

    try {
      // 监听事件上报结果
      UmengCommonSdk.onEvent(eventId, properties ?? {});
      debugPrint('事件触发成功: $eventId, 参数: $properties');
      return true;
    } catch (e) {
      debugPrint('事件触发失败: $eventId, 错误: $e');
      return false;
    }
  }

  static Future<bool> onProfileSignIn(String userID) async {
    if (!_isInitialized) return false;

    try {
      UmengCommonSdk.onProfileSignIn(userID);
      debugPrint('用户登录成功: $userID');
      return true;
    } catch (e) {
      debugPrint('用户登录失败: $userID, 错误: $e');
      return false;
    }
  }

  static Future<bool> onProfileSignOff() async {
    if (!_isInitialized) return false;

    try {
      UmengCommonSdk.onProfileSignOff();
      debugPrint('用户登出成功');
      return true;
    } catch (e) {
      debugPrint('用户登出失败: $e');
      return false;
    }
  }

  static Future<bool> reportError(String error) async {
    if (!_isInitialized) return false;

    try {
      UmengCommonSdk.reportError(error);
      debugPrint('错误上报成功: $error');
      return true;
    } catch (e) {
      debugPrint('错误上报失败: $error, 错误: $e');
      return false;
    }
  }
}
